import React, { useState } from 'react';
import {
  Typography,
  Box,
  Button,
  TextField,
  Grid,
  Card,
  CardContent,
  CircularProgress,
} from '@mui/material';
import { ApiService } from '../services/api';
import { Transaction } from '../types/api';
import { API_CONFIG } from '../config';

interface TransactionSectionProps {
  node: keyof typeof API_CONFIG.NODES;
}

export const TransactionSection: React.FC<TransactionSectionProps> = ({ node }) => {
  const [transaction, setTransaction] = useState<string>('');
  const [txId, setTxId] = useState<string>('');
  const [result, setResult] = useState<Transaction | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      setLoading(true);
      setError(null);

      // 解析用户输入的交易内容
      let parsedTransaction;
      try {
        parsedTransaction = JSON.parse(transaction);
      } catch (parseError) {
        setError('交易内容格式错误，请输入有效的JSON格式');
        return;
      }

      // 使用RepChain示例格式
      const repchainTransaction = {
        stype: 2,
        idPath: "",
        idName: generateTransactionId(),
        iptFunc: `write({'${parsedTransaction.from}':${parsedTransaction.amount}});write({'${parsedTransaction.to}':${parsedTransaction.amount}});`,
        iptArgs: [],
        timeout: 0,
        secureContext: "string",
        code: "string",
        ctype: 0
      };

      console.log('Submitting RepChain transaction:', repchainTransaction);

      const response = await ApiService.postTransaction(node, repchainTransaction);
      console.log('Transaction response:', response);
      
      if (response && response.result) {
        setTxId(response.result);
        // 尝试获取交易详情
        try {
          const txResponse = await ApiService.getTransaction(node, response.result);
          if (txResponse && txResponse.result) {
            setResult(txResponse.result);
          }
        } catch (txErr) {
          console.log('Could not fetch transaction details:', txErr);
        }
      } else {
        setError(`提交失败: ${response?.message || '未知错误'}`);
      }
    } catch (err) {
      setError(`提交交易失败: ${err instanceof Error ? err.message : '未知错误'}`);
      console.error('Error submitting transaction:', err);
    } finally {
      setLoading(false);
    }
  };

  // 生成简单的交易ID
  const generateTransactionId = () => {
    return Date.now().toString(16) + Math.random().toString(16).substr(2);
  };

  return (
    <div className="bg-white shadow rounded-lg p-6">
      <h2 className="text-xl font-semibold mb-4">交易</h2>
      <form onSubmit={handleSubmit} className="space-y-4">
        <div>
          <label htmlFor="transaction" className="block text-sm font-medium text-gray-700">
            交易内容 (JSON格式)
          </label>
          <textarea
            id="transaction"
            value={transaction}
            onChange={(e) => setTransaction(e.target.value)}
            className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
            rows={4}
            placeholder='{"from": "userA", "to": "userB", "amount": 100, "type": "carbon_trade"}'
          />
        </div>
        <button
          type="submit"
          disabled={loading}
          className="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
        >
          {loading ? '提交中...' : '提交交易'}
        </button>
      </form>

      {error && (
        <div className="mt-4 text-red-500 bg-red-50 p-4 rounded-md">
          <p className="font-medium">错误:</p>
          <p>{error}</p>
        </div>
      )}

      {txId && (
        <div className="mt-4">
          <h3 className="font-medium">交易ID</h3>
          <p className="mt-2 p-2 bg-gray-50 rounded-md font-mono text-sm">{txId}</p>
        </div>
      )}

      {result && (
        <div className="mt-4">
          <h3 className="font-medium">交易结果</h3>
          <pre className="mt-2 p-4 bg-gray-50 rounded-md overflow-auto">
            {JSON.stringify(result, null, 2)}
          </pre>
        </div>
      )}
    </div>
  );
};

export default TransactionSection; 